package com.donkey.util;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Web 应用常用功能函数
 *
 * @author hemj
 * @date 2015-07-02
 */
public final class WebUtils {

	/**
	 * 返回客户端IP(ip1[,ip2][,ip3])
	 * <p>
	 * 在apache+WebLogic整合系统中，apache会对request对象进行再包装，附加一些WLS要用的头信息。这种情况下，
	 * 直接用request.getRemoteAddr()是无法取到真正的客户IP的。
	 * </p>
	 */
	public static String getClientIpAddrs(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 返回客户端IP(只返回 getClientIpAddrs 中的第一条IP)
	 */
	public static String getClientIpAddr(HttpServletRequest req) {
		String addr = getClientIpAddrs(req);
		if (addr != null) {
			addr = addr.replaceAll(",.+", "");
		}
		return addr;
	}

	/** 简化 response 输出Map/List对象内容 */
	public static boolean jsonResponse(HttpServletResponse response, Object obj) {
		try {
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write(JSONObject.toJSONString(obj));
			writer.flush();
			writer.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/** 简化 response 输出文本内容 */
	public static boolean codeResponse(HttpServletResponse resp, String resultCode) {
		return WebUtils.textResponse(resp, "{\"result_code\":\"" + resultCode + "\"}");
	}

	/** 简化 response 输出文本内容 */
	public static boolean codeResponse(HttpServletResponse resp, String resultCode, String resultMsg) {
		return WebUtils.textResponse(resp, "{\"result_code\":\"" + resultCode
				+ "\",\"result_msg\":\"" + resultMsg + "\"}");
	}

	/** 简化 response 输出文本内容 */
	public static boolean textResponse(HttpServletResponse response, String str) {
		try {
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write(str);
			writer.flush();
			writer.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}
